var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var compression = require('compression');//压缩静态文件

var cluster = require('cluster');
var os = require('os');
var numCPUs = os.cpus().length;//CPU数量


var settings=require('./config');

/*var session = require('express-session');
var SessionStore = require('express-mysql-session');*/
var dbConfig = require('./dbConfig');
/*var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;*/
/*var pass = require('./utils/pass');*/

var jwt = require('express-jwt');
var secret = require('./utils/secret');
/*var tokenManager = require('./utils/token_manager');
*/

var routes = require('./routes/index');
var users = require('./routes/users');
var carrier = require('./routes/carrier');
var message = require('./routes/message');
var admin = require('./routes/admin');
var wechat = require('wechat');
var multer  = require('multer');//处理文件上传
var app = express();

/*var options = {
    host: dbConfig.host,
    port: dbConfig.port,
    user: dbConfig.user,
    password: dbConfig.password,
    database: dbConfig.database,
    checkExpirationInterval: 7200000,//频繁过期会话将会被清除 ；毫秒为单位
    expiration: 7200000,//过期时间
    createDatabaseTable: true//创建表
}*/
/*var sessionStore = new SessionStore(options);*/


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(favicon());
app.use(logger('dev'));

app.use(compression({level:9}));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(multer({
    dest: './public/image/uploads/',
    limits: {
        fieldNameSize: 100,
        files: 2,
        fileSize: 2048*1024//最大上传2M图片
    },onFileUploadComplete: function (file)  {

        console .log( "upload complete" );

    }
    /*,onFileUploadStart: function (file)  {

        console .log( "upload start" );

    }*/
    /*,
     onFileSizeLimit: function (file) {
     console.log('Failed: ', file.originalname);
     fs.unlink('./uploads/' + file.path) // delete the partially written file
     }*/
}));//处理文件上传

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


/*
app.use(session({
    //key: 'session_cookie',
    secret: 'keyboard cat',
    store:sessionStore,//会话存储实例
    resave: true,
    saveUninitialized: true//"未初始化"将其保存到存储的会话
}));

app.use(passport.initialize());
app.use(passport.session());
*/
app.use(jwt({ secret: secret.secretToken}).unless({path: ['/','/transfer','/carrier','/feedback','/subText','/users/login','/users/resetPass','/initmenu/initmenu','/queryPrice','/getCityList','/users/register','/index/register','/users/getCode','/index/getCode','/admin/manage','/admin/login','/carrier/login','/weixin','/tel.html']}));

//app.use('/weixin', wechat(settings.wc_token).text(function (message, req, res, next) {
//
//    //响应微信服务器已经处理此条消息
//    res.end("");
//
//
//
//}).image(function (message, req, res, next) {
//    // TODO
//    //响应微信服务器已经处理此条消息
//    res.end("");
//
//    // //消息存储
//    /*new util_tool().saveMsg(message, function (err) {
//     debug("add new Message", err);
//     })*/
//}).voice(function (message, req, res, next) {
//    //响应微信服务器已经处理此条消息
//    res.end("");
//
//}).video(function (message, req, res, next) {
//    //响应微信服务器已经处理此条消息
//    res.end("");
//
//}).location(function (message, req, res, next) {
//    // TODO
//}).link(function (message, req, res, next) {
//    // TODO
//}).event(function (message, req, res, next) {
//    // TODO
//    //响应微信服务器已经处理此条消息
//    res.end("");
//    //咨询师在线
//    i
//}).middlewarify());

var config = {
    token: settings.wc_token,
    appid: settings.wc_appid,
    encodingAESKey: settings.encodingAESKey
};

//app.use(express.query());
app.use('/weixin', wechat(config, function (req, res, next) {
    // message is located in req.weixin
    console.log(req.weixin);
    var message = req.weixin;
    if (message.EventKey === 'V100_TELPHONE') {
        // device text
        res.reply('客服热线：<a href="tel:4006556756">4006556756</a>');
    }
}));



app.use(function(req,res,next){
    var url = req.originalUrl;
    /*if(url.indexOf('admin')&&req.user!=null){
        console.log('sssssss');
    }*/
    next();
});

app.use('/', routes);
app.use('/users',users);
app.use('/carrier',carrier);
app.use('/initmenu',message);
app.use(function(req,res,next){
    if(req.user!=null&&req.user.usertype!=3){//管理员类型才能继续执行
        res.render('login',{msg:''});
    }else{
        next();
    }

});
app.use('/admin',admin);


/*app.post('/login',pass.postlogin);//登录认证
app.get('/logOut',pass.logout);//退出登录*/

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    //next(err);
    res.redirect('index.html');
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

/*app.set('port', process.env.PORT || 80);

var server = app.listen(app.get('port'), function() {
    //debug('Express server listening on port ' + server.address().port);
});*/


if (cluster.isMaster) {
    console.log('[master] ' + "start master...");
    var workers;
    for (var i = 0; i < numCPUs; i++) {
        workers = cluster.fork();//创建一个子进程
    }

    cluster.on('listening', function (worker, address) {
        console.log('[主进程] ' + 'listening: worker' + worker.id + ',pid:' + worker.process.pid + ', Address:' + address.address + ":" + address.port);
    });

    /**
     * 工作进程退出后重启
     */
    cluster.on('exit', function(worker, code, signal) {
        var exitCode = worker.process.exitCode;
        console.log('工作进程 ' + worker.process.pid + ' 被结束（'+exitCode+'）。正在重启...');
        cluster.fork();
    });

} else if (cluster.isWorker) {
    console.log('[worker] ' + "start worker ....................." + cluster.worker.id);
    /* http.createServer(function (req, res) {
     console.log('worker'+cluster.worker.id);
     res.end('worker'+cluster.worker.id+',PID:'+process.pid);
     }).listen(3000);*/
    app.set('port', process.env.PORT || 80);
    var server = app.listen(app.get('port'), function() {
        //debug('Express server listening on port ' + server.address().port);
    });
}



module.exports = app;
